package sgd.tp2.server.net.tcp;

import java.io.DataInputStream;
import java.io.IOException;

import sgd.tp2.api.cdr.CDR;
import sgd.tp2.api.cdr.CDRHandlerByteArray;
import sgd.tp2.api.logging.Log;
import sgd.tp2.api.net.CDRFormatType;
import sgd.tp2.api.net.CEPType;

public class TCPServerBytes extends TCPServer {

	public TCPServerBytes(CDRFormatType cdrFormatType, int port, CEPType cepType) {
		super(cdrFormatType, port, cepType);
	}

	@Override
	public void run() {
		DataInputStream inStream = null;
		int byteArrayLen = 0;
		byte[] receivedBytesArray = null;

		try {
			inStream = new DataInputStream(socket.getInputStream());

			while ((byteArrayLen = inStream.readInt()) != 0) {
				receivedBytesArray = new byte[byteArrayLen];
				inStream.readFully(receivedBytesArray, 0, byteArrayLen);

				receivedCDR();

				handleBytes(receivedBytesArray);
			}

		} catch (IOException e) {
			Log.infoln("");
			Log.warningln("Parou de receber. Servidor terminado");
			stopServer();
			return;
		}
	}

	public void handleBytes(byte[] bytes) {
		startCDRHandling();

		CDR cdr = null;
		try {
			cdr = CDRHandlerByteArray.getCDRFromByteArray(bytes);
		} catch (Exception e) {
			Log.warningln("Impossivel transformar o array de bytes em object CDR");
		}
		handleCDR(cdr);

		endCDRHandling(cdr);
	}
}
